package com.member.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.util.*;

public class RestfulUtil {

    private static final Logger log = LoggerFactory.getLogger(RestfulUtil.class);

    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("zxgxsj", "2024-04-10 11:02:12");
//        String a = doAction(HttpAddress.ORDER_ADDRESS, jsonObject);
    }

    /**
     * restful接口调用案例
     * 以getModeDataPageList为例
     */
    public static String doAction(String httpAddress, String userName, JSONObject mainTableTo) {
        CloseableHttpResponse response;// 响应类,
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //restful接口url
        HttpPost httpPost = new HttpPost(httpAddress);

        //当前日期
        String currentDate = getCurrentDate();
        //当前时间
        String currentTime = getCurrentTime();
        //获取时间戳
        String currentTimeTamp = getTimestamp();

        Map<String, Object> params = new HashMap<>();
        Map<String, Object> paramDataJson = new HashMap<>();


        //header
        Map<String, Object> header = new HashMap<>();

        //系统标识
        //密码
        String d_password = "2345@com";
        //封装header里的参数
        header.put("systemid", userName);
        header.put("currentDateTime", currentTimeTamp);
        String md5Source = userName + d_password + currentTimeTamp;
        String md5OfStr = getMD5Str(md5Source).toLowerCase();
        //Md5是：系统标识+密码+时间戳 并且md5加密的结果
        header.put("Md5", md5OfStr);
        paramDataJson.put("header", header);

        //封装pageinfo
        JSONObject pageInfo = new JSONObject();
        pageInfo.put("pageNo", "1");
        pageInfo.put("pageSize", "10000");
        paramDataJson.put("pageInfo", pageInfo);
        //封装mainTable参数
        JSONObject mainTable = new JSONObject();
        mainTable.put("id", "1");
        if (null == mainTableTo) {
            paramDataJson.put("mainTable", mainTable);
        } else {
            paramDataJson.put("mainTable", mainTableTo);
        }
        //封装operationinfo参数
        JSONObject operationinfo = new JSONObject();
        operationinfo.put("operator", "15273");
        paramDataJson.put("operationinfo", operationinfo);

        params.put("datajson", paramDataJson);
        log.info("===请求参数dataJson - {}", params);
        //装填参数
        List<BasicNameValuePair> nvps = new ArrayList<>();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            nvps.add(new BasicNameValuePair(entry.getKey(), JSONObject.toJSONString(entry.getValue())));
        }
        try {
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            response = httpClient.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                //返回信息
                String resulString = EntityUtils.toString(response.getEntity());
                //todo 这里处理返回信息
                JSONObject jsonObject = JSONObject.parseObject(resulString);
                //                log.info("成功" + result);
                return jsonObject.get("result").toString();
            } else {
                log.info("获取数据失败，请查看日志" + currentDate + " " + currentTime);
                return StringUtils.EMPTY;
            }
        } catch (Exception e) {
            log.info("请求失败" + currentDate + " " + currentTime + "====errormsg:" + e.getMessage());
            return StringUtils.EMPTY;
        }
    }


    /**
     * restful接口调用案例
     * 以getModeDataPageList为例
     */
    public static String doAction2(String httpAddress, String userName, JSONObject mainTableTo) {
        CloseableHttpResponse response;// 响应类,
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //restful接口url
        HttpPost httpPost = new HttpPost(httpAddress);

        //当前日期
        String currentDate = getCurrentDate();
        //当前时间
        String currentTime = getCurrentTime();
        //获取时间戳
        String currentTimeTamp = getTimestamp();

        Map<String, Object> params = new HashMap<>();
        Map<String, Object> paramDataJson = new HashMap<>();


        //header
        Map<String, Object> header = new HashMap<>();

        //系统标识
        //密码
        String d_password = "2345@com";
        //封装header里的参数
        header.put("systemid", userName);
        header.put("currentDateTime", currentTimeTamp);
        String md5Source = userName + d_password + currentTimeTamp;
        String md5OfStr = getMD5Str(md5Source).toLowerCase();
        //Md5是：系统标识+密码+时间戳 并且md5加密的结果
        header.put("Md5", md5OfStr);
//        paramDataJson.put("header", header);

        if (null == mainTableTo) {
            //封装pageinfo
            JSONObject pageInfo = new JSONObject();
            pageInfo.put("pageNo", 1);
            pageInfo.put("pageSize", 1000);
            paramDataJson.put("pageInfo", pageInfo);
        }
        //封装mainTable参数
        JSONObject mainTable = new JSONObject();
        mainTable.put("id", "1");
        if (null == mainTableTo) {
            paramDataJson.put("mainTable", mainTable);
        } else {
            paramDataJson.put("mainTable", mainTableTo);
        }
        //封装operationinfo参数
        JSONObject operationinfo = new JSONObject();
        operationinfo.put("operator", "15273");
        paramDataJson.put("operationinfo", operationinfo);

        List<Map<String, Object>> list = new ArrayList<>();
        list.add(paramDataJson);
        JSONObject a = new JSONObject();
        a.put("data", list);
        a.put("header", header);
        params.put("datajson", a);
        JSONObject b = new JSONObject();
        b.put("datajson", a);
        log.info("===请求参数params - {}", b);

        //装填参数
        List<BasicNameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("datajson", b.get("datajson").toString()));
        try {
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            response = httpClient.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                //返回信息
                String resulString = EntityUtils.toString(response.getEntity());
                //todo这里处理返回信息
                JSONObject jsonObject = JSONObject.parseObject(resulString);
                String result = jsonObject.get("status").toString();
                log.info(result);
//                if (result.equals("1")) {
//                    log.info("成功" + jsonObject.get("datajson").toString());
//                } else {
//                    log.info("失败" + jsonObject.get("datajson").toString());
//                }
                return result;
            } else {
                log.info("获取数据失败，请查看日志" + currentDate + " " + currentTime);
                return StringUtils.EMPTY;
            }
        } catch (Exception e) {
            log.info("请求失败" + currentDate + " " + currentTime + "====errormsg:" + e.getMessage());
            return StringUtils.EMPTY;
        }
    }

    /**
     * restful接口调用案例
     * 以getModeDataPageList为例
     */
    public static String doAction3(String httpAddress, String userName, JSONObject mainTableTo) {
        CloseableHttpResponse response;// 响应类,
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //restful接口url
        HttpPost httpPost = new HttpPost(httpAddress);

        //当前日期
        String currentDate = getCurrentDate();
        //当前时间
        String currentTime = getCurrentTime();
        //获取时间戳
        String currentTimeTamp = getTimestamp();

        Map<String, Object> params = new HashMap<>();
        Map<String, Object> paramDataJson = new HashMap<>();


        //header
        Map<String, Object> header = new HashMap<>();

        //系统标识
        //密码
        String d_password = "2345@com";
        //封装header里的参数
        header.put("systemid", userName);
        header.put("currentDateTime", currentTimeTamp);
        String md5Source = userName + d_password + currentTimeTamp;
        String md5OfStr = getMD5Str(md5Source).toLowerCase();
        //Md5是：系统标识+密码+时间戳 并且md5加密的结果
        header.put("Md5", md5OfStr);
        paramDataJson.put("header", header);

        //封装pageinfo
        JSONObject pageInfo = new JSONObject();
        pageInfo.put("pageNo", "1");
        pageInfo.put("pageSize", "10000");
        paramDataJson.put("pageInfo", pageInfo);
        //封装mainTable参数
        JSONObject mainTable = new JSONObject();
        mainTable.put("id", "1");
        if (null == mainTableTo) {
            paramDataJson.put("mainTable", mainTable);
        } else {
            paramDataJson.put("mainTable", mainTableTo);
        }
        //封装operationinfo参数
        JSONObject operationinfo = new JSONObject();
        operationinfo.put("operator", "15273");
        paramDataJson.put("operationinfo", operationinfo);

        params.put("datajson", paramDataJson);
        log.info("===请求参数dataJson - {}", params);
        //装填参数
        List<BasicNameValuePair> nvps = new ArrayList<>();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            nvps.add(new BasicNameValuePair(entry.getKey(), JSONObject.toJSONString(entry.getValue())));
        }
        try {
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            response = httpClient.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                //返回信息
                String resulString = EntityUtils.toString(response.getEntity());
                //todo 这里处理返回信息
                JSONObject jsonObject = JSONObject.parseObject(resulString);
                //                log.info("成功" + result);
                JSONObject result = JSON.parseObject(jsonObject.get("result").toString());

                return result.get("mainTable").toString();
            } else {
                log.info("获取数据失败，请查看日志" + currentDate + " " + currentTime);
                return StringUtils.EMPTY;
            }
        } catch (Exception e) {
            log.info("请求失败" + currentDate + " " + currentTime + "====errormsg:" + e.getMessage());
            return StringUtils.EMPTY;
        }
    }

    public static String getMD5Str(String plainText) {
        //定义一个字节数组
        byte[] secretBytes = null;
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            //对字符串进行加密
            md.update(plainText.getBytes());
            //获得加密后的数据
            secretBytes = md.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有md5这个算法！");
        }
        //将加密后的数据转换为16进制数字
        StringBuilder md5code = new StringBuilder(new BigInteger(1, secretBytes).toString(16));
        // 如果生成数字未满32位，需要前面补0
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code.insert(0, "0");
        }
        return md5code.toString();
    }

    public static String getCurrentTime() {
        Date newDate = new Date();
        long datetime = newDate.getTime();
        Timestamp timestamp = new Timestamp(datetime);
        return (timestamp.toString()).substring(11, 13) + ":" + (timestamp.toString()).substring(14, 16) + ":"
                + (timestamp.toString()).substring(17, 19);
    }

    public static String getCurrentDate() {
        Date newDate = new Date();
        long datetime = newDate.getTime();
        Timestamp timestamp = new Timestamp(datetime);
        return (timestamp.toString()).substring(0, 4) + "-" + (timestamp.toString()).substring(5, 7) + "-"
                + (timestamp.toString()).substring(8, 10);
    }

    /**
     * 获取当前日期时间。 YYYY-MM-DD HH:MM:SS
     *
     * @return 当前日期时间
     */
    public static String getCurDateTime() {
        Date newDate = new Date();
        long datetime = newDate.getTime();
        Timestamp timestamp = new Timestamp(datetime);
        return (timestamp.toString()).substring(0, 19);
    }

    /**
     * 获取时间戳   格式如：19990101235959
     *
     * @return
     */
    public static String getTimestamp() {
        return getCurDateTime().replace("-", "").replace(":", "").replace(" ", "");
    }

    public static int getIntValue(String v, int def) {
        try {
            return Integer.parseInt(v);
        } catch (Exception ex) {
            return def;
        }
    }

    public static String null2String(Object s) {
        return s == null ? "" : s.toString();
    }

}
